package com.kelvem.saas.workbanch.ontology.piaoorder.handle.core;

import com.kelvem.saas.workbanch.fsm.container.DaoContainer;
import com.kelvem.saas.workbanch.fsm.dao.BaseDao;
import com.kelvem.saas.workbanch.fsm.entity.Entity;
import com.kelvem.saas.workbanch.fsm.container.EntityMapppingContainer;
import com.kelvem.saas.workbanch.fsm.entity.EntityMapppingNode;
import com.kelvem.saas.workbanch.fsm.core.EventContext;
import com.kelvem.saas.workbanch.fsm.handle.Handle;
import com.kelvem.saas.workbanch.ontology.piaoorder.model.PiaoOrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

/**
 * @author kelvem
 */
@Service
@Slf4j
public class PersistencePiaoOrderHandle extends Handle {
    
    @Override
    public void execute() {
        
        List<Entity> entityList = EventContext.getEntityList(); // todo 依赖关系, 该方法重写
        for (Entity entity :
                entityList) {
            log.info("PersistencePiaoOrderHandle, insertSelective, " + entity.getClass().toString());
    
            // 设置关联id
            EntityMapppingNode mapping = EntityMapppingContainer.getMapping(entity.getClass());
            if (mapping != null) {
                // 获取关联对象主键
                Class<Entity> rihgtClazz = (Class<Entity>) mapping.getRightClazz();
                Entity right = Entity.instance().selectOne(rihgtClazz);
                Long rightId = right.getId();
    
                try {
                    // 设置entity的值
                    Field leftField = entity.getClass().getDeclaredField(mapping.getLeftKey());
                    leftField.setAccessible(true);
                    leftField.set(entity, rightId);
                    log.debug(entity.getClass().getSimpleName() + "." + leftField.getName() + " setValue " + rightId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
            // create_time
            if (entity.getCreateTime() == null) {
                entity.setCreateTime(new Date());
            }
            // update_time
            entity.setUpdateTime(new Date());
            
            BaseDao dao = DaoContainer.getDao(entity.getClass());
            if (entity.getId() == null) {
                dao.insert(entity);
            } else {
                dao.updateById(entity);
            }
        }
        
        PiaoOrderEntity order = Entity.instance().selectOne(PiaoOrderEntity.class);
    
        log.info("Handle[" + getName() + "] orderId=" + order.getId());
        EventContext.print();
    }
}
